package com.svoice;

import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.google.common.base.Strings;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.dictionary.py.Pinyin;

import java.util.List;
import java.util.Map;

/**
 * @program: study
 * @className: SvoiceData
 * @description: TODO
 * @author: kukuxiahuni
 * @create: 2019-12-20 18:44
 * @version: v1.0
 **/
public class SvoiceData {

    public static void main(String[] args) {
        SvoiceData svoiceData = new SvoiceData();
//        svoiceData.read();
        toJson();
    }

    public static final void toJson() {
//        ExcelWriter writer = ExcelUtil.getWriter("/Users/kukuxiahuni/Desktop/b.xlsx");
        ExcelReader excelReader = ExcelUtil.getReader("/Users/kukuxiahuni/Desktop/b.xlsx");
        List<Map<String, Object>> readAll = excelReader.readAll();
        System.out.println(JSONUtil.toJsonStr(readAll));

    }

    public final void read() {

        String file = "/Users/kukuxiahuni/Desktop/a.xlsx";
        ExcelReader excelReader = ExcelUtil.getReader(file);
        List<Map<String, Object>> readAll = excelReader.readAll();

        for (Map<String, Object> map : readAll) {
            String word = String.valueOf(map.getOrDefault("指令词", ""));
            map.put("拼音", this.covertToPinyin(word, " "));
        }
        ExcelWriter writer = ExcelUtil.getWriter("/Users/kukuxiahuni/Desktop/b.xlsx");
        writer.write(readAll, true);
//关闭writer，释放内存
        writer.close();

    }

    public String covertToPinyin(String text, String delimiter) {
        if (Strings.isNullOrEmpty(text)) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        List<Pinyin> pinyinList = HanLP.convertToPinyinList(text);

        for (Pinyin pinyin : pinyinList) {
            stringBuilder.append(pinyin.getPinyinWithoutTone());
            stringBuilder.append(delimiter);
        }

        int index = stringBuilder.lastIndexOf(delimiter);
//
//        return stringBuilder.substring(0, index).toLowerCase();
        String result = stringBuilder.toString().replaceAll("(?<=j|q|x)(u){1}(?=\\s)+", "v").substring(0, index);
        return result;
    }


}
